/** 
 * Map 地图类
*/

class Map {
    constructor(el, rect = 10) {
        this.rect = rect; // 每个格子大小
        this.el = el;
        this.data = [];
        this.rows = Math.ceil(Map.getStyle(el, 'height') / rect); // 行数
        this.cells = Math.ceil(Map.getStyle(el, 'width') / rect); // 列数
        Map.setStyle(el, 'height', this.rows * rect);
        Map.setStyle(el, 'width', this.cells * rect);
    }

    static getStyle(el, attr) {
        return parseFloat(getComputedStyle(el)[attr]);
    }

    static setStyle(el, attr, val) {
        el.style[attr] = val + 'px';
    }

    render() {
        this.el.innerHTML = this.data.map(item => {
            const {
                x,
                y,
                color
            } = item;
            return `<span style='position:absolute;width:${this.rect}px;height:${this.rect}px;left:${x*this.rect}px;top:${y*this.rect}px;background:${color}'></span>`
        });
    }

    // 设置数据
    setData(newData) {
        this.data = this.data.concat(newData);
    }

    // 清空数据
    clearData() {
        this.data.length = 0;
    }

    // 判断当前数据是否包含该坐标
    include({
        x,
        y
    }) {
        return this.data.some(item => (item.x === x && item.y === y));
    }
}

export default Map;